// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let {
    op,
    _id,
    _openid,
    status,
    mch
  } = event
  switch (op) {
    case 'apply':
      return apply()
      break;
    case 'review':
      return review()
      break;
    case 'getMchs':
      return getMchs()
      break;
    case 'getMchInfo':
      return getMchInfo()
      break;
  }
  async function apply() {
    let res = await db.collection("Merchant").where({
      _openid: wxContext.OPENID
    }).get()

    if (res.data.length > 0)
      return 'applied'

    let data = mch
    data._openid = wxContext.OPENID
    data.createTime = db.serverDate()
    data.status = 0 //0-申请中，1-审核通过，2-审核拒绝

    let result = await db.collection('Merchant').add({
      data: data
    })
    return result
  }
  async function review() {
    let result = await db.collection('Merchant').doc(_id).update({
      data: {
        status: parseInt(status),
        review_id: wxContext.OPENID,
        review_time: db.serverDate()
      }
    })

    return result
  }
  async function getMchs() {

    const countResult = await db.collection('Merchant').where({
      status: parseInt(status)
    }).count()
    const total = countResult.total

    let result = await db.collection('Merchant')
      .aggregate()
      .match({
        status: parseInt(status)
      })

      .lookup({
        from: 'User',
        localField: '_openid',
        foreignField: '_openid',
        as: 'user',
      })
      .end()

    let list = result.list
    for (let i = 0; i < list.length; i++) {
      list[i].nickname = list[i].user[0].nickname
      list[i].avatar = list[i].user[0].avatar
      delete list[i].user
    }


    return {
      total: total,
      list: result.list
    }
  }
  async function getMchInfo() {
    let result = await db.collection('Merchant').where({
      _openid: wxContext.OPENID,
      // status:1
    }).get()
    return result.data[0]
  }
}